package com.estate.system.service.message;

import com.alibaba.fastjson2.JSONObject;
import com.estate.system.domain.pojo.GenerateMessageReq;
import com.estate.system.domain.pojo.GenerateMessageVo;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class EmailGeneratorClientOkHttp {

    private static final Logger log = LoggerFactory.getLogger(EmailGeneratorClientOkHttp.class);

    private static final String API_URL = "http://47.84.74.41:8001/generate-email/";
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    public String generateEmail(GenerateMessageVo generateMessageVo) {
        log.info("generateEmail: " + JSONObject.toJSONString(generateMessageVo));
        GenerateMessageReq generateMessageReq = new GenerateMessageReq();
        generateMessageReq.setClient_id(generateMessageVo.getClientId());
        generateMessageReq.setAgent_id(generateMessageVo.getAgentId());
        generateMessageReq.setEnquiry_type(generateMessageVo.getEnquiryType());
        generateMessageReq.setListing_ids(generateMessageVo.getListingIds());
        //String json = "{\"client_id\": "+ generateMessageVo.getClientId() +", \"agent_id\": "+generateMessageVo.getAgentId()+", \"enquiry_type\": \""+ generateMessageVo.getEnquiryType() +"\"}";
        String json = JSONObject.toJSONString(generateMessageReq);
        // 创建 OkHttpClient 并设置超时时间
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)  // 连接超时
                .readTimeout(60, TimeUnit.SECONDS)     // 读取超时
                .writeTimeout(30, TimeUnit.SECONDS)    // 写入超时
                .build();

        RequestBody body = RequestBody.create(json, JSON);
        Request request = new Request.Builder()
                .url(API_URL)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                String responseBody = response.body().string();
                log.info("Response: " + responseBody);
                return responseBody;
            } else {
                log.error("Request failed: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
